import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, routes } from '@/router'
const sha256 = require('js-sha256').sha256

const getDefaultState = () => {
  return {
    token: getToken(),
    avatar: '',
    routes: [],
    addRoutes: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_MENU_ROUTES: (state, routes) => {
    state.routes = routes
  },
  SET_ROUTES: (state, accessedRoutes) => {
    state.addRoutes = accessedRoutes
    state.routes = routes.concat(accessedRoutes)
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

/**
 * 构造异步侧边栏
 * @param routes asyncRoutes
 */
export function filterAsyncRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.ismenu === 1) {
      const component = route.component.toLowerCase()
      const StandardRouting = {
        path: route.path,
        // 异步 component
        component: resolve => require([`@/views/${component}`], resolve),
        name: route.name,
        meta: route.meta,
        hidden: route.ismenu !== 1 || route.hidden === 1 // 是否为侧边栏
      }

      // 递归
      if ('children' in route) {
        StandardRouting.children = filterAsyncRoutes(route.children)
      }

      // 推进数组
      res.push(StandardRouting)
    }
  })

  return res
}

/**
 * 重新格式化 menu 所需的路由数据
 * @param {*} list
 * @returns
 */
export function formatRouters(list) {
  const routers = []
  list.forEach((route) => {
    if (!route.hidden) {
      if (route.children) {
        if (route.children.length > 1) {
          routers.push(route)
        } else {
          routers.push(route.children[0])
        }
      }
    }
  })
  return routers
}

const actions = {
  // user login
  login({ dispatch, commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const param = {
        account: userInfo.account,
        accountPwd: sha256(userInfo.accountPwd)
      }
      login(userInfo.checkCode, param, userInfo.token).then(response => {
        const { code, data } = response
        resolve(response)
        if (code === 4005) {
          return
        }
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        dispatch('basicSettings/getMyInfo', null, { root: true })
      }).catch(error => {
        reject(error)
      })
    })
  },

  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(roles)
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', accessedRoutes)
      const menuRoutes = formatRouters(accessedRoutes)
      commit('SET_MENU_ROUTES', menuRoutes)
      resolve(accessedRoutes)
    })
  },
  // user logout
  logout({ dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        // 清除所有缓存
        dispatch('user/resetToken', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ dispatch, commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      resetRouter()
      dispatch('basicSettings/localStorageCleaner', null, { root: true })
      dispatch('exercises/reset_exercises_data_acion', null, { root: true })
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

